%% @author Administrator
%% @doc @todo Add description to user_svr_util.


-module(user_svr_util).

-include("net.hrl").
-include("config.hrl").

%% ====================================================================
%% API functions
%% ====================================================================
-export([show_server_list/0,
		 link/1,
		 link/2,
		 client_link_svr/2]).



%% ====================================================================
%% Internal functions
%% ====================================================================

show_server_list() ->
	ServerList = cfg_server:gets(),
	io:format("=================  ServerList ====================~n~n"),
	[begin #cfg_server{name = Name} = cfg_server:get(Id),
    	   Name1 = unicode:characters_to_list(list_to_binary(Name)),
		   io:format("[~p]"++Name1++"~n", [Id]) 
	 end||Id<-ServerList],
	
	io:format("==================================================~n~n").

link(CfgServerId) ->
	case cfg_server:get(CfgServerId) of
		#cfg_server{ip = IP, port = Port} ->
			link(IP, Port);
		_ ->
			io:format("CfgServerId Undef")
	end.

link(IP, Port) ->
	Reply = gen_server:call(user_svr, {client_link_svr, IP, Port}, ?GEN_SERVER_CALL_TIME_OUT),
	io:format("Reply: ~p",[Reply]).
		


%% @doc 客户端连接服务端 - user_svr调用
client_link_svr(IP, Port) ->
	case gen_tcp:connect(IP, Port, [], ?CONNECT_TIME_OUT) of
		{ok, Socket} ->
			io:format("Link Successful!!!~n~n"),
			case player_svr_util:start_link([IP, Port, Socket]) of
				{ok, Pid} ->
					case gen_tcp:controlling_process(Socket, Pid) of
						ok ->
							Ret = "Start Player Successful!!!~n~n",
							io:format(Ret),
							Ret;
						_ ->
							Ret = "Sorry Control Access Fail.~n~n",
							io:format(Ret),
							Ret
					end;
				_ ->
					Ret = "Sorry, Start Player Fail.~n~n",
					io:format(Ret),
					Ret
			end;
		_ ->
			Ret = "Sorry,Link Fail. Please Check Your Network.~n~n",
			io:format(Ret),
			Ret
	end.
